<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Cases;
use App\Models\News;
use App\Models\Product;
use App\Models\Service;
use App\Models\Video;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function __invoke(Request $request)
    {
        $q = $request->input('q');
        $limit = $q ? 99 : 10;
        $per_page = $request->input('per_page') ?? $limit;

        $callback = function ($query) use ($q) {
            $query->where('title', 'like', '%' . $q . '%');
        };

        // service
        $services = Service::when($q, $callback)->take($per_page)->get();

        // cases
        $cases = Cases::when($q, $callback)->take($per_page)->get();

        // products
        $products = Product::when($q, $callback)->take($per_page)->get();

        // news
        $news = News::when($q, $callback)->take($per_page)->get();

        // videos
        $videos = Video::when($q, $callback)->take($per_page)->get();

        return $this->successful(compact('services', 'cases', 'products', 'news', 'videos'));
    }
}
